#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/12/15 21:24
# @Author  : FuKai ZHANG
# @File    : allure_report_data.py
# @Description :
import json
from typing import List
from config.setting import ensure_path_sep
from utils.file_operation.get_all_file_path import get_all_files
from utils.models.models import TestMetrics

""" allure report data 
"uid": "610f992b59b322ea",
  "name": "异常登录，非注册用户登录",
  "fullName": "test_case.test_login_case.TestLoginCase#test_login",
  "historyId": "5a66c0c926e21365525d215cbd5d999a",
  "time": {
    "start": 1702636682027,
    "stop": 1702636682123,
    "duration": 96
  },
  "status": "passed",

.......
"""


class AllureFileClean:
    """提取allure报告中需要的数据"""

    def __init__(self):
        # 先拿到allure里面所有用例执行的json文件名
        self.get_allure_case = get_all_files(ensure_path_sep("\\report\\html\\data\\test-cases"))

    def get_testcases(self) -> List:
        """ 获取所有 allure 报告中执行用例的情况"""
        # 将所有数据都收集到files中
        all_allure_case_data = []
        for i in self.get_allure_case:
            with open(i, 'r', encoding='utf-8') as file:
                date = json.load(file)
                all_allure_case_data.append(date)
        return all_allure_case_data

    def get_failed_case(self) -> List:
        """ 获取到所有失败的用例标题和用例路径"""
        error_case = []
        for i in self.get_testcases():
            if i['status'] == 'failed' or i['status'] == 'broken':
                error_case.append((i['name'], i['fullName']))
        return error_case

    @classmethod
    def get_case_count(cls) -> "TestMetrics":
        """ 统计用例数量 """
        try:
            file_name = ensure_path_sep("\\report\\html\\widgets\\summary.json")
            with open(file_name, 'r', encoding='utf-8') as file:
                data = json.load(file)
            _case_count = data['statistic']
            _time = data['time']
            keep_keys = {"passed", "failed", "broken", "skipped", "total"}
            run_case_data = {k: v for k, v in data['statistic'].items() if k in keep_keys}
            # 判断运行用例总数大于0
            if _case_count["total"] > 0:
                # 计算用例成功率
                run_case_data["pass_rate"] = round(
                    (_case_count["passed"] + _case_count["skipped"]) / _case_count["total"] * 100, 2
                )
            else:
                # 如果未运行用例，则成功率为 0.0
                run_case_data["pass_rate"] = 0.0
            # 收集用例运行时长
            run_case_data['time'] = _time if run_case_data['total'] == 0 else round(_time['duration'] / 1000, 2)
            return TestMetrics(**run_case_data)
        except FileNotFoundError as exc:
            raise FileNotFoundError(
                "程序中检查到您未生成allure报告，"
                "通常可能导致的原因是allure环境未配置正确，"
            ) from exc


if __name__ == '__main__':
    print(AllureFileClean().get_case_count())
